package fpt.edu.vn.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fpt.edu.vn.dao.TopicsDao;
import fpt.edu.vn.model.Districts;
import fpt.edu.vn.model.Provinces;
import fpt.edu.vn.util.SolrQuerying;

/* 
 * FullTextSearchAction.java 
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class FullTextSearchAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private List<Object> mostView;
	private String Username;
	// Các tin đã xem
	private List<Object> recentView;
	public static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";
	private int city;
	private int district;
	private int area;
	private int price;
	private int topictypeid;
	private String name;
	private String keysearch;
	private int sortby;
	private InputStream inputStream;
	private List<Provinces> provinces;
	private List<Districts> districts;
	private SolrQuerying solQ = new SolrQuerying();
	private List<Map<String, Object>> lstTopic = new ArrayList<Map<String, Object>>();
	private TopicsDao dao = new TopicsDao();

	// For SessionAware
	Map<String, Object> session;
	public String getkeysearch(){
		session = ActionContext.getContext().getSession();
		if("Tìm Kiếm ...".equals(decodeURIComponent(keysearch)))
			keysearch="";
		if(keysearch!=null)
			session.put("keysearch", keysearch);
		inputStream = toUTF8InputStream("Okie");
		return SUCCESS;
	}
	public static InputStream toUTF8InputStream(String str) {
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// UTF-8 should always be supported
			throw new AssertionError();
		}
		return is;
	}
	public String execute() {
		this.provinces = dao.listProvinces();
		this.districts = dao.listDistricts();
		this.mostView = dao.listMostView();
		String displayNamess = "";
		session = ActionContext.getContext().getSession();
		String ipaddress = "";

		if (session.containsKey("ipaddress")) {
			ipaddress = (String) session.get("ipaddress");
		}

		this.recentView = dao.listRecentView(ipaddress);
		if (session.containsKey("displayNamess")) {
			displayNamess = (String) session.get("displayNamess");
		}
		if ("".equals(displayNamess) || displayNamess == null) {
			setUsername(null);
		} else {
			setUsername(displayNamess);
		}
		try {
			solQ.updateDataFromMysqlToSolr();
			if (session.containsKey("keysearch")) {
				name = decodeURIComponent(session.get("keysearch").toString());
			}
			lstTopic = solQ.Fulltext(name ,sortby,0);
			if(lstTopic.size()==0){
				lstTopic = solQ.Fulltext(name ,sortby,1);
				if(lstTopic.size()==0){
					lstTopic = solQ.Fulltext(name ,sortby,2);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public static String decodeURIComponent(String encodedURI) {
		char actualChar;

		StringBuffer buffer = new StringBuffer();

		int bytePattern, sumb = 0;

		for (int i = 0, more = -1; i < encodedURI.length(); i++) {
			actualChar = encodedURI.charAt(i);

			switch (actualChar) {
			case '%': {
				actualChar = encodedURI.charAt(++i);
				int hb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				actualChar = encodedURI.charAt(++i);
				int lb = (Character.isDigit(actualChar) ? actualChar - '0'
						: 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
				bytePattern = (hb << 4) | lb;
				break;
			}
			case '+': {
				bytePattern = ' ';
				break;
			}
			default: {
				bytePattern = actualChar;
			}
			}

			if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx
				sumb = (sumb << 6) | (bytePattern & 0x3f);
				if (--more == 0)
					buffer.append((char) sumb);
			} else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
				buffer.append((char) bytePattern);
			} else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
				sumb = bytePattern & 0x1f;
				more = 1;
			} else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
				sumb = bytePattern & 0x0f;
				more = 2;
			} else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx
				sumb = bytePattern & 0x07;
				more = 3;
			} else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx
				sumb = bytePattern & 0x03;
				more = 4;
			} else { // 1111110x
				sumb = bytePattern & 0x01;
				more = 5;
			}
		}
		return buffer.toString();
	}
	public List<Map<String, Object>> getLstTopic() {
		return lstTopic;
	}

	public void setLstTopic(List<Map<String, Object>> lstTopic) {
		this.lstTopic = lstTopic;
	}
	
	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public String getName() {
		return name;
	}
	
	public String getKeysearch() {
		return keysearch;
	}
	public void setKeysearch(String keysearch) {
		this.keysearch = keysearch;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public int getSortby() {
		return sortby;
	}

	public void setSortby(int sortby) {
		this.sortby = sortby;
	}

	public Date getSysdate() {
		Date date = new Date();
		return date;
	}

	public String getStrDate() {
		String curdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(Calendar.getInstance().getTime());
		return curdate;
	}

	public List<Object> getMostView() {
		return mostView;
	}

	public void setMostView(List<Object> mostView) {
		this.mostView = mostView;
	}

	public List<Provinces> getProvinces() {
		return provinces;
	}

	public void setProvinces(List<Provinces> provinces) {
		this.provinces = provinces;
	}

	public String getUsername() {
		return Username;
	}

	public void setUsername(String username) {
		Username = username;
	}

	public int getCity() {
		return city;
	}

	public void setCity(int city) {
		this.city = city;
	}

	public int getArea() {
		return area;
	}

	public void setArea(int area) {
		this.area = area;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public TopicsDao getDao() {
		return dao;
	}

	public void setDao(TopicsDao dao) {
		this.dao = dao;
	}

	public int getDistrict() {
		return district;
	}

	public void setDistrict(int district) {
		this.district = district;
	}

	public List<Object> getRecentView() {
		return recentView;
	}

	public void setRecentView(List<Object> recentView) {
		this.recentView = recentView;
	}

	public int getTopictypeid() {
		return topictypeid;
	}

	public void setTopictypeid(int topictypeid) {
		this.topictypeid = topictypeid;
	}

	public List<Districts> getDistricts() {
		return districts;
	}

	public void setDistricts(List<Districts> districts) {
		this.districts = districts;
	}

}
